package mrms.api.web.authentication;

import lombok.AllArgsConstructor;
import mrms.api.entity.UserEntity;
import mrms.api.repository.UserRepository;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author lenchu
 * @date 2019/02/03
 */
@Component
@Order(100)
@AllArgsConstructor
public class IdPasswordAuthentication implements Authentication {
    private final UserRepository userRepository;
    private final JwtUtils jwtUtils;

    @Override
    public void authenticate(HttpServletRequest request, HttpServletResponse response, Map<String, Object> requestBody) {
        Object user = request.getAttribute("user");
        if (user != null && user instanceof UserEntity) {
            return;
        }
        Optional<UserEntity> userEntityOptional = userRepository.findById((String) requestBody.get("id"));
        List<String> errors = (List<String>) requestBody.get("errors");
        if (userEntityOptional.isPresent()) {
            UserEntity userEntity = userEntityOptional.get();
            if (userEntity.getPassword().equals(Encipher.encryptPasswordWithMD5((String) requestBody.get("password")))) {
                request.setAttribute("user", userEntity);
            } else {
                errors.add("用户名和密码不匹配");
            }
        } else {
            errors.add("无此用户");
        }
    }
}
